<?php
namespace app\admin\controller;

use think\Request;

class Menu extends Auth
{

    //菜单列表 @author leiqianyong 2020-8-8 13:39 PM
    public function index() {
        $pid=input('pid',0);

        $obj=model('menu');
        $top = $obj->where("id={$pid} AND hide_flag=0")->find();
        $list=$obj->where("pid={$pid} AND hide_flag=0")->order('level ASC,sort DESC')->select()->toArray();

        $this->assign('top',$top);
        $this->assign('list',$list);
        return $this->fetch();
    }


    //编辑添加
    public function edit(){
        $id = input('id');
        $pid = input('pid',0);
        $obj=model('menu');

        if(request()->isAjax() || request()->isPost()){
            $data['title']=input('title','','trim');
            if(!$data['title'])$this->error('请输入菜单名称');
            $data['path']=input('path','','trim');
            $data['pid']=$pid;
            $data['is_show']=input('is_show');
            $data['manage_show']=input('manage_show');
            $data['icon']=input('icon','','trim');

            //等级
            $level = 1 ;
            if($pid){
                $plevel = $obj->where("id",$pid)->value('level');
                $level  = $plevel?($plevel+1):1;
            }
            $data['level'] = $level ;

            //添加修改数据
            $this->editDataMethod($data,$obj);
        }

        $this->assign('pid',$pid);
        if($id) {
            $info = $obj->where("id",$id)->find();
            $this->assign('info', $info);
            $pid = $info['pid'];
        }

        $tree=$this->getTree($pid);
        $this->assign('menu',$tree);
        return $this->fetch();
    }


    //删除菜单
    public function del(){
        $id=input('id');
        if(!$id)return false;
        $map['id']=$id;
        $obj=model('menu');
        $umap['pid']=$id;
        if($obj->where($umap)->find())$this->error('有下级菜单，不能删除 !');

        $res=$obj->where($map)->delete();
        if(!$res)$this->error('删除失败');
        $this->success('删除成功');
    }


    //获取菜单的树形结构
    public function getTree($pid){
        require '../extend/lib/tree.class.php';
        $tree = new \tree();
        $list=model('menu')->where("hide_flag=0")->order("sort DESC,id DESC")->select()->toArray();
        foreach($list as $val)$ary[$val['id']]=$val;

        $tree->init($ary);
        //$tree->icon = array('&nbsp;│ ','&nbsp;├─ ','&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $str  = "<option value='\$id' \$selected>\$spacer\$title</option>";
        $categorys = $tree->get_tree(0,$str,$pid);
        return $categorys;
    }


}
